from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from neo4j.exceptions import Neo4jError

from config.neo4j_client import get_neo4j_driver


class Command(BaseCommand):
    help = "Verify connectivity to the configured Neo4j instance and print server info."

    def handle(self, *args, **options):
        self.stdout.write(f"Connecting to Neo4j at {settings.NEO4J_URI} ...")

        try:
            driver = get_neo4j_driver()
            driver.verify_connectivity()
        except Neo4jError as exc:
            raise CommandError(f"Unable to connect to Neo4j: {exc}") from exc
        except Exception as exc:  # pragma: no cover - guard unexpected errors
            raise CommandError(f"Neo4j configuration error: {exc}") from exc

        try:
            with driver.session() as session:
                record = session.run(
                    """
                    CALL dbms.components() YIELD name, versions, edition
                    RETURN name, head(versions) AS version, edition
                    """
                ).single()
        except Neo4jError as exc:
            raise CommandError(f"Connected but failed to query server metadata: {exc}") from exc

        if not record:
            raise CommandError("Connected to Neo4j but no component information was returned.")

        name = record["name"]
        version = record["version"]
        edition = record["edition"]

        self.stdout.write(
            self.style.SUCCESS(
                f"Neo4j connection OK - {name} {version} ({edition}). "
                "Ready for knowledge graph features."
            )
        )
